package com.dy.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dy.convert.UserConvert;
import com.dy.dto.UserDTO;
import com.dy.dto.UserLoginDTO;
import com.dy.entity.User;
import com.dy.mapper.UserMapper;
import com.dy.service.UserService;
import com.dy.utils.BadCustomException;
import com.dy.vo.UserVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Author: dy
 * @date: 2024/5/7 12:47
 * @ClassDescription:
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserConvert userConvert;

    /**
     * 用户注册
     * @param dto dto
     * @return {@link Boolean}
     */
    @Override
    public Boolean register(UserDTO dto) {
        User user = userConvert.userDtoToUser(dto);
        //校验账户名称不能重复
        Integer count = this.lambdaQuery()
                .eq(User::getUserName, dto.getUserName())
                .count();
        if (count > 0) {
            throw new BadCustomException("账户名称已存在");
        }
        //密码明文加密
        String passwordMd5 = SecureUtil.md5(dto.getPassword());
        user.setPassword(passwordMd5);
        //明文密码
        user.setPasswordPlainText(dto.getPassword());
        return this.save(user);
    }

    /**
     * 登录
     * @param dto dto
     * @return {@link UserVO}
     */
    @Override
    public UserVO login(UserLoginDTO dto) {
        User user = this.lambdaQuery()
                .eq(User::getUserName, dto.getUserName())
                .one();
        if (user == null) {
            throw new BadCustomException("用户不存在");
        }
        String passwordMd5 = SecureUtil.md5(dto.getPassword());
        if (!passwordMd5.equals(user.getPassword())) {
            throw new BadCustomException("用户名或密码错误");
        }
        StpUtil.login(user.getId());
        UserVO userVO = new UserVO();
        userVO.setToken(StpUtil.getTokenValue())
                .setNickName(user.getNickName());
        return userVO;
    }
}
